<template>
    <el-dialog v-model="isShowDialog" :title="updateForm.id ? '编辑' : '新增'" width="600" :before-close="closeDialog">
      <!-- 校验规则为rules，直接定义所有参数的rules，但是<el-form-item>中的prop还是要设置，且还需要新增一个interface -->
      <el-form ref="updateFormRef" :model="updateForm" :rules="updateFormRules">
        <el-form-item label="角色名" :label-width="formLabelWidth" prop="roleName" :rules="[
          { required: true, message: '角色名不能为空', trigger: 'blur' }
        ]">
          <el-input v-model="updateForm.roleName" placeholder="请输入角色名"/>
        </el-form-item>

        <el-form-item label="权限" :label-width="formLabelWidth" prop="permissionIdList">
        <el-tree style="max-width: 600px;"
          ref="checkedPermissionTreeRef"
          :data="permissionTreeList"
          default-expand-all
          node-key="id"
          show-checkbox
          :props="props"
          highlight-current
          />
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog()">取消</el-button>
          <el-button type="primary" @click="submitUpdateForm(updateFormRef)">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </template>
  <script lang="ts" setup>
  import { reactive,ref } from 'vue';
  import type { FormInstance, FormRules } from 'element-plus';
  import { ElMessage, ElLoading, ElTree } from 'element-plus';
  import { post, postWithToken } from '~/composables/utils';
  import { TreeKey } from 'element-plus/es/components/tree/src/tree.type';
  const updateFormRef = ref<FormInstance>();
  // 展示弹框的参数
  const isShowDialog = ref(false);
  // 弹框里面label的宽度
  const formLabelWidth = '80px';
  // 回调父页面
  const emit = defineEmits(['refresh']);
  // 弹框里面的form
  const updateForm = reactive<UpdateRoleForm>({
      id:null,
      roleName: '',
      permissionIdList: []
  });
  const permissionTreeList = ref<any>();
  const checkedPermissionTreeRef = ref<InstanceType<typeof ElTree>>();
  // 弹框里面的form对应的interface
  interface UpdateRoleForm {
    id:number | null;
    roleName: string;
    permissionIdList: TreeKey[];
  }

  // 校验权限的规则
  const validatePermissionTree = (rule: any, value: any, callback: any) => {
    if (checkedPermissionTreeRef.value!.getCheckedKeys(false).length == 0) {
      callback(new Error('权限不能为空'));
    } else {
      callback();
    }
  }
  // 新增更新用户弹框的form规则
  const updateFormRules = reactive<FormRules<typeof updateForm>>({
    permissionIdList: [{ required: true, validator: validatePermissionTree, trigger: 'blur' }]
  });
  
  const submitUpdateForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
      if (valid) {
        addOrUpdateUser();
      } else {
        console.log('error submit!')
      }
    })
  };
  
  // 新增更新数据
  const addOrUpdateUser =  async () => {
    try {
      const loadingInstance = ElLoading.service({fullscreen: true});
      var response ;
      updateForm.permissionIdList = checkedPermissionTreeRef.value!.getCheckedKeys(false);
      if (updateForm.id) {
        response = await postWithToken('/role/updateRole', updateForm);
      } else {
        response = await postWithToken('/role/saveRole', updateForm);
      }
      loadingInstance.close();
      if (response.code != 200) {
          ElMessage.error(response.msg);
      } else {
          ElMessage.success((updateForm.id ? '修改' : '新增') + '角色成功！');
          closeDialog();
      }
    } catch (error) {
      console.error('There was an error!', error);
    }
  };
  
  // 查询权限树
const queryPermissionTree = async () => {
  try {
    const response = await postWithToken('/permission/permissionTree');
    if (response.code != 200) {
        ElMessage.error(response.msg);
    } else {
      // 设置表数据
      permissionTreeList.value = response.data;
    }
  } catch (error) {
    console.error('There was an error!', error);
  }
};

  // 查询角色的权限
  const getPermissionByRole = async (roleId:number) => {
  try {
    const response = await postWithToken('/permission/getPermissionByRole', {roleId : roleId});
    if (response.code != 200) {
        ElMessage.error(response.msg);
    } else {
      // 设置已选择的权限
      checkedPermissionTreeRef.value!.setCheckedKeys(response.data, false);
    }
  } catch (error) {
    console.error('There was an error!', error);
  }
};


// interface Tree {
//   id: number,
//   permissionName: string
//   children?: Tree[]
// }

const props = {
  id: 'id',
  label: 'permissionName',
  children: 'childrenList'
}

  function closeDialog() {
    isShowDialog.value = false;
    clearForm();
    // 回调父页面的@refresh，刷新页面
    emit('refresh');
  }
  // 重置数据
  const clearForm = () => {
    updateForm.id = null;
    updateForm.roleName = '';
    // permissionTreeList.value = [];
    // updateForm.permissionIdList = [];
    checkedPermissionTreeRef.value?.setCheckedKeys([]);
  }
  
  
  const init = (data?: UpdateRoleForm) => {
    isShowDialog.value = true;
    if (data) Object.assign(updateForm, data);
    queryPermissionTree();
    if (updateForm.id) {
      getPermissionByRole(updateForm.id);
    }
  };
  defineExpose({ init });
  </script>
  <style lang="scss">
  /* 为了页面刷新不出现滚动条 */
  .ep-scrollbar {
    height: auto;
  }
/*  ::v-deep(.el-table__row:not([class*='el-table__row--level-'])) {
    td:first-child{
      padding-left: 24px;
    }
  }
  :deep(.el-tree-node__expand-icon.expanded){
    transform: rotate(90deg);
  }

  .ep-tree-node__children .ep-tree-node__content{
    padding-left: 100px;
  }
    */
  </style>